package com.qingzhu.controller.addressserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.Areas;
import com.qingzhu.pojo.Cities;
import com.qingzhu.pojo.Provinces;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.AddressService;
import com.qingzhu.service.impl.AddressServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/address")
public class AddressController extends HttpServlet {
    AddressService addressService = new AddressServiceImpl();
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("地址查找服务..");
        String serverName = req.getParameter("server");

        if (serverName != null && serverName.equals("provinces")){
            findProvinces(req,resp);
        }else if (serverName != null && serverName.equals("city")) {
            findByProvincesId(req,resp);
        }else if (serverName != null && serverName.equals("areas")) {
            findByCitiesId(req,resp);
        }else {
            resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1001,"服务器类型标记为空")));
        }
    }


    // 查询所有的省份信息
    public void findProvinces(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Provinces> provincesList = addressService.findProvinces();
        resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,provincesList)));
    }
    // 根据省id查询所有归属的城市
    public void findByProvincesId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String provinceId = req.getParameter("provinceId");
        List<Cities> citiesList = addressService.findByProvincesId(provinceId);
        resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,citiesList)));
    }
    // 根据城市id查询所有归属的区域
    public void findByCitiesId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String cityId = req.getParameter("cityId");
        List<Areas> areas = addressService.findByCitiesId(cityId);
        resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,areas)));
    }
}
